<template>
    <Layout>
        <div class="announcement-details">
            <!-- 面包屑导航 -->
            <div class="breadcrumb">
                当前位置：<router-link to="/home" class="breadcrumb-link">首页</router-link> > <router-link to="/volunteer-elegance" class="breadcrumb-link">志愿风采</router-link> > <span class="breadcrumb-current">详情</span>
            </div>

            <div class="announcement-content">
                <h1 class="title">{{ announcement.title }}</h1>
                
                <div class="meta-info">
                    <span><el-icon><Calendar /></el-icon>{{ formatDate(announcement.publishTime) }}</span>
                    <span><el-icon><User /></el-icon>{{ announcement.author }}</span>
                    <span><el-icon><View /></el-icon>{{ announcement.views }} 次浏览</span>
                </div>

                <div class="content">
                    <div v-if="announcement.imageUrl" class="image-container">
                        <el-image :src="announcement.imageUrl" fit="contain"></el-image>
                    </div>
                    <div class="text-content" v-html="announcement.content"></div>
                </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-section">
                <h2 class="comments-title">评论区</h2>
                
                <!-- 发表评论 -->
                <div class="comment-form">
                    <el-input
                        v-model="newComment"
                        type="textarea"
                        :rows="3"
                        placeholder="写下你的想法..."
                        class="comment-input"
                    >
                    </el-input>
                    <el-button type="primary" @click="submitComment" class="submit-btn" round>
                        发表评论
                    </el-button>
                </div>

                <!-- 评论列表 -->
                <div class="comments-list">
                    <div v-if="comments.length === 0" class="no-comments">
                        <el-empty description="暂无评论，来发表第一条评论吧！"></el-empty>
                    </div>
                    <div v-else v-for="comment in comments" :key="comment.id" class="comment-item">
                        <div class="comment-header">
                            <div class="comment-user-info">
                                <el-avatar :size="40" class="user-avatar">{{ comment.username[0] }}</el-avatar>
                                <div class="user-details">
                                    <span class="comment-author">{{ comment.username }}</span>
                                    <span class="comment-time">{{ formatDate(comment.commentTime) }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="comment-content">
                            {{ comment.content }}
                        </div>
                        <div class="comment-actions">
                            <el-button type="primary" text @click="toggleLike(comment)" class="like-button" :class="{ 'liked': comment.isLiked }">
                                <img src="@/assets/like.svg" class="like-icon" />
                                <span class="like-count" style="margin-top: 5px;margin-left: 10px;">{{ comment.likeCount }}</span>
                            </el-button>
                            <el-button type="primary" text @click="showReplyInput(comment)" class="reply-button">
                                回复
                            </el-button>
                        </div>

                        <!-- 回复输入框 -->
                        <div v-if="comment.showReplyInput" class="reply-form">
                            <el-input
                                v-model="comment.replyContent"
                                type="textarea"
                                :rows="2"
                                placeholder="写下你的回复..."
                                class="reply-input"
                            >
                            </el-input>
                            <div class="reply-actions">
                                <el-button type="primary" @click="submitReply(comment)" size="small">提交回复</el-button>
                                <el-button @click="hideReplyInput(comment)" size="small">取消</el-button>
                            </div>
                        </div>

                        <!-- 回复列表 -->
                        <div class="replies-list" v-if="comment.replies && comment.replies.length > 0">
                            <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                                <div class="reply-user-info">
                                    <el-avatar :size="30" class="reply-avatar">{{ reply.userName[0] }}</el-avatar>
                                    <span class="reply-author">{{ reply.userName }}</span>
                                    <span class="reply-time">{{ formatDate(reply.replyTime) }}</span>
                                </div>
                                <div class="reply-content">
                                    {{ reply.content }}
                                </div>
                                <div class="reply-actions">
                                    <el-button type="primary" text @click="toggleReplyLike(reply)" class="like-button" :class="{ 'liked': reply.isLiked }">
                                        <img src="@/assets/like.svg" class="like-icon" />
                                        <span class="like-count">{{ reply.likeCount || 0 }}</span>
                                    </el-button>
                                    <el-button type="primary" text @click="showSecondReplyInput(reply)" class="reply-button">
                                        回复
                                    </el-button>
                                </div>
                                
                                <!-- 二级回复输入框 -->
                                <div v-if="reply.showSecondReplyInput" class="reply-form second-level">
                                    <el-input
                                        v-model="reply.secondReplyContent"
                                        type="textarea"
                                        :rows="2"
                                        placeholder="回复..."
                                        class="reply-input"
                                    >
                                    </el-input>
                                    <div class="reply-actions">
                                        <el-button type="primary" @click="submitSecondReply(reply, comment)" size="small">提交</el-button>
                                        <el-button @click="hideSecondReplyInput(reply)" size="small">取消</el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </Layout>
</template>

<script setup>
import Layout from '@/components/Layout.vue'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const announcement = ref({
    title: '',
    content: '',
    author: '',
    publishTime: '',
    views: 0,
    imageUrl: ''
})

const comments = ref([])
const newComment = ref('')

const formatDate = (date) => {
    if (!date) return ''
    return new Date(date).toLocaleDateString('zh-CN')
}

const submitComment = async () => {
    if (!newComment.value.trim()) {
        ElMessage.warning('评论内容不能为空')
        return
    }

    try {
        const commentData = {
            userId: localStorage.getItem('volunteerId'),
            commentId: route.params.id,
            userType: localStorage.getItem('type'),
            content: newComment.value,
            commentTime: new Date().toISOString(),
            likeCount: 0
        }
        const response = await axios.post('http://localhost:9090/VolunteerViewComment/add', commentData)
        
        if (response.data) {
            ElMessage.success('评论发表成功')
            newComment.value = ''
            fetchComments()
        }
    } catch (error) {
        console.error('发表评论失败:', error)
        ElMessage.error('发表评论失败')
    }
}

const fetchComments = async () => {
    try {
        const response = await axios.get(`http://localhost:9090/VolunteerViewComment/news/${route.params.id}`)
        if (response.data) {
            comments.value = response.data.map(comment => ({
                ...comment,
                isLiked: false,
                showReplyInput: false,
                replyContent: '',
                replies: []
            }))
            // 获取每个评论的回复
            for (let comment of comments.value) {
                await fetchReplies(comment)
            }
        }
    } catch (error) {
        console.error('获取评论列表失败:', error)
    }
}

const fetchReplies = async (comment) => {
    try {
        const response = await axios.get(`http://localhost:9090/api/reply/${comment.id}`)
        if (response.data) {
            comment.replies = response.data.map(reply => ({
                ...reply,
                isLiked: false,
                showSecondReplyInput: false,
                secondReplyContent: '',
                userType: reply.userId // 临时使用userId作为userType显示
            }))
        }
    } catch (error) {
        console.error('获取回复列表失败:', error)
    }
}

const showReplyInput = (comment) => {
    comment.showReplyInput = true
}

const hideReplyInput = (comment) => {
    comment.showReplyInput = false
    comment.replyContent = ''
}

const showSecondReplyInput = (reply) => {
    reply.showSecondReplyInput = true
}

const hideSecondReplyInput = (reply) => {
    reply.showSecondReplyInput = false
    reply.secondReplyContent = ''
}

const submitReply = async (comment) => {
    if (!comment.replyContent.trim()) {
        ElMessage.warning('回复内容不能为空')
        return
    }

    try {
        const replyData = {
            userId: localStorage.getItem('volunteerId'),
            commentId: comment.id,
            content: comment.replyContent,
            replyTime: new Date().toISOString(),
            likeCount: 0,
            parentReplyId: null
        }
        const response = await axios.post('http://localhost:9090/api/reply', replyData)
        
        if (response.data) {
            ElMessage.success('回复发表成功')
            hideReplyInput(comment)
            await fetchReplies(comment) // 重新获取回复列表
        }
    } catch (error) {
        console.error('发表回复失败:', error)
        ElMessage.error('发表回复失败')
    }
}

const submitSecondReply = async (reply, comment) => {
    if (!reply.secondReplyContent.trim()) {
        ElMessage.warning('回复内容不能为空')
        return
    }

    try {
        const replyData = {
            userId: localStorage.getItem('volunteerId'),
            commentId: comment.id,
            content: reply.secondReplyContent,
            replyTime: new Date().toISOString(),
            likeCount: 0,
            parentReplyId: reply.id
        }
        const response = await axios.post('http://localhost:9090/api/reply', replyData)
        
        if (response.data) {
            ElMessage.success('回复发表成功')
            hideSecondReplyInput(reply)
            await fetchReplies(comment) // 重新获取回复列表
        }
    } catch (error) {
        console.error('发表二级回复失败:', error)
        ElMessage.error('发表回复失败')
    }
}

const toggleLike = async (comment) => {
    try {
        const updatedComment = {
            id: comment.id,
            userId: comment.userId,
            commentId: comment.commentId,
            userType: comment.userType,
            content: comment.content,
            commentTime: comment.commentTime,
            likeCount: comment.isLiked ? comment.likeCount - 1 : comment.likeCount + 1
        }
        await axios.put('http://localhost:9090/VolunteerViewComment/update', updatedComment)
        comment.likeCount = updatedComment.likeCount
        comment.isLiked = !comment.isLiked
        ElMessage.success(comment.isLiked ? '点赞成功' : '已取消点赞')
    } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
    }
}

const toggleReplyLike = async (reply) => {
    try {
        const updatedReply = {
            id: parseInt(reply.id),
            userId: parseInt(reply.userId),
            commentId: parseInt(reply.commentId),
            content: reply.content,
            replyTime: reply.replyTime,
            likeCount: parseInt(reply.isLiked ? (reply.likeCount || 0) - 1 : (reply.likeCount || 0) + 1),
            parentReplyId: reply.parentReplyId ? parseInt(reply.parentReplyId) : null
        }
        console.log(updatedReply)
        await axios.put('http://localhost:9090/api/reply/update', updatedReply)
        reply.likeCount = updatedReply.likeCount
        reply.isLiked = !reply.isLiked
        ElMessage.success(reply.isLiked ? '点赞成功' : '已取消点赞')
    } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
    }
}

onMounted(async () => {
    const id = route.params.id
    try {
        const response = await axios.get(`http://localhost:9090/api/volunteerview/${id}`)
        if (response.data) {
            announcement.value = response.data
        }
        await fetchComments()
    } catch (error) {
        console.error('获取公告详情失败:', error)
    }
})
</script>

<style scoped>
.announcement-details {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Microsoft YaHei', sans-serif;
}

.breadcrumb {
    margin-bottom: 20px;
    color: #666;
    font-size: 14px;
    padding: 10px 0;
    border-bottom: 1px dashed #eaeaea;
}

.breadcrumb-link {
    color: #dd2b2b;
    text-decoration: none;
    transition: all 0.3s ease;
}

.breadcrumb-link:hover {
    color: #ff4d4d;
    text-decoration: underline;
}

.breadcrumb-current {
    color: #dd2b2b;
    font-weight: 500;
}

.announcement-content {
    background: #fff;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    margin-bottom: 30px;
    transition: all 0.3s ease;
}

.announcement-content:hover {
    box-shadow: 0 6px 25px rgba(0,0,0,0.12);
    transform: translateY(-3px);
}

.title {
    text-align: center;
    font-size: 28px;
    color: #303133;
    margin-bottom: 25px;
    font-weight: 600;
    position: relative;
    padding-bottom: 15px;
}

.title::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 80px;
    height: 3px;
    background: linear-gradient(to right, #dd2b2b, #ff6b6b);
    border-radius: 3px;
}

.meta-info {
    display: flex;
    justify-content: center;
    gap: 30px;
    color: #909399;
    font-size: 14px;
    margin-bottom: 30px;
    border-bottom: 1px solid #EBEEF5;
    padding-bottom: 20px;
}

.meta-info span {
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s ease;
}

.meta-info span:hover {
    color: #dd2b2b;
    transform: translateY(-2px);
}

.content {
    color: #606266;
    line-height: 1.8;
}

.image-container {
    margin: 25px 0;
    text-align: center;
    overflow: hidden;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.image-container .el-image {
    max-width: 100%;
    border-radius: 8px;
    transition: all 0.5s ease;
}

.image-container .el-image:hover {
    transform: scale(1.02);
}

.text-content {
    font-size: 16px;
    text-align: justify;
    line-height: 1.8;
    color: #333;
}

/* 评论区样式 */
.comments-section {
    background: #fff;
    padding: 35px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

.comments-section:hover {
    box-shadow: 0 6px 25px rgba(0,0,0,0.12);
}

.comments-title {
    margin-bottom: 35px;
    font-size: 24px;
    color: #303133;
    font-weight: 600;
    position: relative;
    padding-left: 18px;
}

.comments-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 5px;
    height: 25px;
    background: linear-gradient(to bottom, #dd2b2b, #ff6b6b);
    border-radius: 3px;
}

.comment-form {
    margin-bottom: 45px;
    position: relative;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 12px;
    transition: all 0.3s ease;
}

.comment-form:hover {
    background: #f5f5f5;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.comment-input {
    border-radius: 10px;
    transition: all 0.3s ease;
    border: 1px solid #e0e0e0;
}

.comment-input:focus {
    box-shadow: 0 0 15px rgba(221,43,43,0.15);
    border-color: #dd2b2b;
}

.submit-btn {
    margin-top: 18px;
    font-size: 16px;
    background: #dd2b2b;
    border: none;
    transition: all 0.3s ease;
    padding: 10px 25px;
    font-weight: 500;
}

.submit-btn:hover {
    background: #ff4d4d;
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(221,43,43,0.3);
}

.comments-list {
    margin-top: 35px;
}

.no-comments {
    text-align: center;
    padding: 50px 0;
    color: #909399;
}

.comment-item {
    padding: 25px;
    border-radius: 12px;
    background: #f8f9fa;
    margin-bottom: 25px;
    transition: all 0.3s ease;
    border-left: 4px solid #dd2b2b;
}

.comment-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 15px rgba(0,0,0,0.08);
    background: #f5f7fa;
}

.comment-header {
    margin-bottom: 18px;
}

.comment-user-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.user-avatar {
    background: linear-gradient(135deg, #dd2b2b, #ff6b6b);
    color: white;
    box-shadow: 0 4px 10px rgba(221,43,43,0.3);
    transition: all 0.3s ease;
}

.user-avatar:hover {
    transform: scale(1.1) rotate(5deg);
}

.user-details {
    display: flex;
    flex-direction: column;
}

.comment-author {
    font-weight: 600;
    color: #303133;
    font-size: 16px;
}

.comment-time {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
}

.comment-content {
    color: #333;
    line-height: 1.7;
    font-size: 15px;
    padding: 12px 0;
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    margin: 10px 0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.comment-actions {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
    gap: 18px;
}

.like-button {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #dd2b2b;
    transition: all 0.3s ease;
    padding: 6px 12px;
    border-radius: 20px;
}

.like-button:hover {
    color: #ff4d4d;
    transform: scale(1.05);
    background: rgba(221,43,43,0.1);
}

.like-button.liked {
    color: #ff4d4d;
    background: rgba(221,43,43,0.1);
}

.like-count {
    font-size: 14px;
    font-weight: 500;
}

.like-icon {
    width: 18px;
    height: 18px;
    transition: all 0.3s ease;
}

.like-button:hover .like-icon {
    transform: scale(1.2);
}

/* 回复相关样式 */
.reply-form {
    margin-top: 18px;
    padding: 18px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 3px 10px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.reply-form:hover {
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
}

.reply-form.second-level {
    margin-left: 45px;
    background: #f8f9fa;
    border-left: 3px solid #dd2b2b;
}

.reply-input {
    margin-bottom: 12px;
    border-radius: 8px;
}

.reply-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.replies-list {
    margin-top: 20px;
    padding-left: 25px;
    border-left: 2px solid #EBEEF5;
}

.reply-item {
    padding: 15px 0;
    border-bottom: 1px solid #EBEEF5;
    transition: all 0.3s ease;
}

.reply-item:hover {
    background: rgba(248,249,250,0.7);
}

.reply-item:last-child {
    border-bottom: none;
}

.reply-user-info {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
}

.reply-avatar {
    background: linear-gradient(135deg, #dd2b2b, #ff6b6b);
    color: white;
    box-shadow: 0 3px 8px rgba(221,43,43,0.25);
    transition: all 0.3s ease;
}

.reply-avatar:hover {
    transform: scale(1.1);
}

.reply-author {
    font-weight: 500;
    color: #303133;
    font-size: 15px;
}

.reply-time {
    color: #909399;
    font-size: 12px;
    margin-left: 8px;
}

.reply-content {
    color: #333;
    font-size: 14px;
    padding-left: 42px;
    line-height: 1.6;
    background: #fff;
    border-radius: 8px;
    padding: 12px 15px 12px 42px;
    margin: 8px 0;
    box-shadow: 0 2px 6px rgba(0,0,0,0.03);
}

.reply-button {
    color: #606266;
    transition: all 0.3s ease;
    border-radius: 20px;
    padding: 5px 12px;
}

.reply-button:hover {
    color: #dd2b2b;
    background: rgba(221,43,43,0.1);
}
</style>
